package vn.com.epi.rest;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import vn.com.epi.web.Application;
import javax.ws.rs.core.Response;

import com.google.common.base.Strings;


@Path("/log")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class Log {

    @Context
    private ServletContext context;

    public Log() {
    }
    
    @SuppressWarnings({ "unused" })
    private boolean isValidLog(String line) {
        try {
            String[] chunks = line.split(",");
            long timestamp = Long.parseLong(chunks[0]);
            if (Strings.isNullOrEmpty(chunks[1]))
                return false;
            int actionId = Integer.parseInt(chunks[2].substring(3, chunks[2].length()));
            if (actionId < 0 || 5 < actionId)
                return false;
            int articleID = Integer.parseInt(chunks[3]);
            int categoryID = Integer.parseInt(chunks[4]);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    
    private String getValidLogs(String lines) {
        try {
            String logs = "";
            String[] lineArr = lines.split("\n");
            for (int i = 0; i < lineArr.length; i++)
                if (isValidLog(lineArr[i])) {
                    if (!Strings.isNullOrEmpty(logs))
                        logs += "\n";
                    logs += lineArr[i];
                }
            return logs;
        } catch (Exception e) {
            return null;
        }
    }

    @POST
    @Consumes("text/plain; charset=UTF-8")
    public Response uploadLog(String lines) throws IOException, InterruptedException {        
        String logs = getValidLogs(lines);
        if (!Strings.isNullOrEmpty(logs)) {
            String[] lineArr = logs.split("\n");
            Application.getLogBuffer().add(context, lineArr);
            return Response.status(201).entity("Processed " + lineArr.length + " lines.").build();
        } else
            return Response.status(201).entity("Invalid log lines.").build();
    }

}
